<template>
  <div class="index">
    <head-text titleText="商城优惠设定"></head-text>
    <div class="list-content ">
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="提前优惠（餐饮）" name="first">
          <el-form
            :model="aheadForm"
            ref="aheadForm"
            label-width="140px"
            class="demo-ruleForm"
            :rules="rules"
          >
            <el-form-item label="是否开启优惠：" required>
              <el-switch
                v-model="isAhead"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </el-form-item>
            <el-form-item
              label="提前优惠："
              prop="discountCondition"
              v-if="isAhead"
            >
              <span> 提前</span>
              <el-input-number
                v-model="aheadForm.discountCondition"
                autocomplete="off"
                style="width:120px;"
                size="mini"
                :min="0"
              ></el-input-number>
              <span> 天预定，打</span>
              <el-input-number
                v-model="aheadForm.discount"
                autocomplete="off"
                style="width:120px;"
                size="mini"
                :min="0"
                :max="10"
              ></el-input-number>
              折
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="Sub(1)" size="mini"
                >保存</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="满减优惠（特许）" name="second">
          <el-form
            :model="fullForm"
            ref="fullForm"
            label-width="140px"
            class="demo-ruleForm"
            :rules="rules2"
          >
            <el-form-item label="是否开启优惠：" required>
              <el-switch
                v-model="isFull"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </el-form-item>
            <el-form-item
              label="满减优惠："
              prop="discountCondition"
              v-if="isFull"
            >
              <span> 全场满</span>
              <el-input-number
                v-model="fullForm.discountCondition"
                autocomplete="off"
                style="width:120px;"
                size="mini"
                :min="0"
              ></el-input-number>
              <span> 件，打</span>
              <el-input-number
                v-model="fullForm.discount"
                autocomplete="off"
                size="mini"
                style="width:120px;"
                :min="0"
                :max="10"
              ></el-input-number>
              折
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="Sub(2)" size="mini"
                >保存</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="特许商品定金比例" name="third">
          <el-form
            :model="payForm"
            status-icon
            ref="payForm"
            label-width="100px"
            class="demo-ruleForm"
            :rules="rules3"
            :disabled="true"
          >
            <el-form-item prop="type" label="比例选择">
              <el-select
                v-model="payForm.type"
                placeholder="请选择类型"
                size="mini"
              >
                <el-option label="0元预定" :value="0"></el-option>
                <el-option label="全额付款" :value="1"></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item>
              <el-button type="primary" @click="paySub()" size="mini"
                >保存</el-button
              >
            </el-form-item> -->
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { _debounce } from "@u/debounce";
import {
  getProportionApi,
  updateProportionApi,
  addProportionApi,
  getDiscountsApi,
  updateDiscountsApi,
  addDiscountsApi
} from "@s/api";
import headText from "@c/headText";
export default {
  name: "index",
  data() {
    // 满减
    var regDis = /^((0\.[1-9]{1})|(([1-9]{1})(\.\d{1})?))$/; //0到 10保留一位小数
    var regFull = /^(\+?[1-9][0-9]*)$/; // 满减不可以为0
    var regAhead = /^(0|\+?[1-9][0-9]*)$/; // 提前可以为0
    var checkFull = (rule, value, callback) => {
      if (value === "" || this.fullForm.discount === "") {
        callback(new Error("输入框不能为空"));
      } else if (!regFull.test(value)) {
        callback(new Error("件数请输入正整数"));
      } else if (!regDis.test(this.fullForm.discount)) {
        callback(new Error("折扣请输入0到10以内的数字，且可保留一位小数"));
      } else {
        callback();
      }
    };
    // 提前
    var checkAhead = (rule, value, callback) => {
      if (value === "" || this.aheadForm.discount === "") {
        callback(new Error("输入框不能为空"));
      } else if (!regAhead.test(value)) {
        callback(new Error("天数请输入0或者正整数"));
      } else if (!regDis.test(this.aheadForm.discount)) {
        callback(new Error("折扣请输入0到10以内的数字，且可保留一位小数"));
      } else {
        callback();
      }
    };
    // 定金比例
    var checkType = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择内容"));
      } else {
        callback();
      }
    };
    return {
      activeName: "first",
      isAhead: false,
      isFull: false,
      aheadForm: {
        discountCondition: "",
        discount: "",
        id: ""
      },
      fullForm: {
        discountCondition: "",
        discount: "",
        id: ""
      },
      payForm: {
        type: "",
        id: ""
      },
      rules: {
        discountCondition: [
          {
            required: true,
            trigger: "blur",
            message: "请选择数值"
          },
          {
            validator: checkAhead
          }
        ]
      },
      rules2: {
        discountCondition: [
          { required: true, trigger: "blur", message: "请选择数值" },
          { validator: checkFull }
        ]
      },
      rules3: {
        type: [
          { required: true, message: "请选择类型", trigger: "blur" },
          {
            validator: checkType
          }
        ]
      }
    };
  },
  components: {
    headText
  },
  mounted() {
    this.getList();
    this.getproportionList();
  },
  methods: {
    getList() {
      getDiscountsApi().then(res => {
        res.list.forEach(item => {
          if (item.discountType == 1) {
            // 开关
            if (item.discountCondition == 0 && item.discount == 0) {
              this.isAhead = false;
            } else {
              this.isAhead = true;
            }
            this.aheadForm = item;
          } else if (item.discountType == 2) {
            // 开关
            if (item.discountCondition == 0 && item.discount == 0) {
              this.isFull = false;
            } else {
              this.isFull = true;
            }
            this.fullForm = item;
          }
        });
      });
    },
    getproportionList() {
      getProportionApi({ limit: 10, page: 1 }).then(res => {
        if (res.list.length > 0) {
          this.payForm.type = res.list[0].depositPercent;
          this.payForm.id = res.list[0].id;
        }
      });
    },
    handleClick() {},
    updateSub(json) {
      updateDiscountsApi(json).then(() => {
        this.$message({
          type: "success",
          message: "修改成功！"
        });
      });
    },
    addSub(json) {
      addDiscountsApi(json).then(() => {
        this.$message({
          type: "success",
          message: "修改成功！"
        });
      });
    },
    Sub: _debounce(function(val) {
      if (val == 1) {
        this.$refs["aheadForm"].validate(valid => {
          if (valid) {
            this.$confirm("此操作将修改该信息?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              if (!this.isAhead) {
                this.aheadForm.discountCondition = 0;
                this.aheadForm.discount = 0;
              }
              let json = {
                discountType: 1,
                discountCondition: this.aheadForm.discountCondition,
                discount: this.aheadForm.discount
              };
              if (this.aheadForm.id) {
                json.id = this.aheadForm.id;
                this.updateSub(json);
              } else {
                this.addSub(json);
              }
            });
          }
        });
      } else {
        this.$refs["fullForm"].validate(valid => {
          if (valid) {
            this.$confirm("此操作将修改该信息?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              if (!this.isFull) {
                this.fullForm.discountCondition = 0;
                this.fullForm.discount = 0;
              }
              let json = {
                discountType: 2,
                discountCondition: this.fullForm.discountCondition,
                discount: this.fullForm.discount
              };
              if (this.fullForm.id) {
                json.id = this.fullForm.id;
                this.updateSub(json);
              } else {
                this.addSub(json);
              }
            });
          }
        });
      }
    }),
    paySub: _debounce(function() {
      this.$refs["payForm"].validate(valid => {
        if (valid) {
          this.$confirm("此操作将修改该信息?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            if (this.payForm.id) {
              let json = {
                id: this.payForm.id,
                depositPercent: this.payForm.type
              };

              updateProportionApi(json).then(() => {
                this.$message({
                  type: "success",
                  message: "修改成功！"
                });
              });
            } else {
              let json = {
                depositPercent: this.payForm.type
              };
              addProportionApi(json).then(() => {
                this.$message({
                  type: "success",
                  message: "修改成功！"
                });
              });
            }
          });
        }
      });
    })
  }
};
</script>
<style scoped lang="scss">
.demo-ruleForm {
  span {
    margin: 0 10px;
  }
}
</style>
